<template>
  <view class="service-ticket-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="异常泊位列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template #right>
            <view @click="handleAdd">新增</view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <view class="search-bar">
            <view class="search-bar-item" @click="showPicker1 = true">
              <text class="title">时间</text>
              <up-icon name="arrow-down"></up-icon>
            </view>

            <view class="time-picker">
              <text class="title"></text>
              <uni-datetime-picker type="daterange" :border="false"></uni-datetime-picker>
            </view>
            <up-picker :show="showPicker1" :columns="columns1" :closeOnClickOverlay="true"
              @confirm="showPicker1 = false" @cancel="showPicker1 = false" @close="showPicker1 = false"></up-picker>
            <up-datetime-picker closeOnClickOverlay :show="showDateTimePicker" v-model="formData.messageDate"
              mode="date" @cancel="hideDateTimePickerModal" @confirm="hideDateTimePickerModal"
              @close="hideDateTimePickerModal"></up-datetime-picker>
          </view>

          <up-search :clearabled="true" :showAction="false" placeholder="请输入泊位号/停车场"></up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="service-ticket-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              泊位号：<text class="number">{{ item.berthNo || '未知' }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  状态
                </text>
                <view class="value">
                  <view class="item-tag">
                    <up-tag :text="auditStatusMap[item.auditStatus] || '未知'" :type="getStatusTagType(item.auditStatus)">
                    </up-tag>
                  </view>
                </view>
              </view>
              <view class="item">
                <text class="label">
                  停车场：
                </text>
                <text class="value">
                  {{ item.veName || '未知' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  异常类型：
                </text>
                <text class="value">
                  {{ errorTypeMap[item.errorType] || '未知' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  异常原因：
                </text>
                <text class="value">
                  {{ item.errorRemark || '无' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  创建时间：
                </text>
                <text class="value">
                  {{ item.createTime || '未知' }}
                </text>
              </view>
              <view class="item" v-if="item.dealTime">
                <text class="label">
                  处理时间：
                </text>
                <text class="value">
                  {{ item.dealTime }}
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="default" text="指派任务" plain class="custom-style" @click="handleApply(item)"
                  v-if="item.auditStatus === 0">
                </up-button>
                <up-button type="primary" text="处理" class="custom-style" @click="handleCheck(item)"
                  v-if="item.auditStatus === 1">
                </up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 模态框组件 -->
    <CheckModal v-model:show="showCheckModal" :rowData="editingData" @confirm="handleRefresh" />
    <AddModal v-model:show="showAddModal" @confirm="handleRefresh" />
    <ApplyModal v-model:show="showApplyModal" :rowData="editingData" @confirm="handleRefresh" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { getErrorBerthList } from '@/api';
import CheckModal from './components/CheckModal.vue'
import ApplyModal from './components/ApplyModal.vue'
import AddModal from './components/AddModal.vue'

const { bool: showCheckModal, setTrue: openCheckModal } = useBoolean();
const { bool: showApplyModal, setTrue: openApplyModal } = useBoolean();
const { bool: showAddModal, setTrue: openAddModal } = useBoolean();
const { bool: showDateTimePicker, setTrue: showDateTimePickerModal, setFalse: hideDateTimePickerModal } = useBoolean();
const type = ref('add')
const editingData = ref({})
const formData = reactive({
  messageDate: ''
})

// 搜索和筛选参数
const searchParams = reactive({
  keyword: '', // 关键字查询
  dateType: 0, // 日期类型 0.近7天 1.近一个月 2.近3个月 3.近6个月 4.近一年
  startDate: '', // 开始日期
  endDate: '', // 结束日期
  isOwn: 0, // 是否本人 0.全部 1.本人
  errorType: -1, // 异常类型 -1.全部 0.违停 1.障碍物 2.非机动车 3.其他原因
})

// 异常类型映射
const errorTypeMap = {
  0: '违停',
  1: '障碍物',
  2: '非机动车',
  3: '其他原因'
}

// 处理状态映射
const auditStatusMap = {
  0: '待指派',
  1: '待处理',
  2: '驳回',
  3: '重新指派',
  4: '已处理',
  5: '关闭',
  99: '取消'
}

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '待处理' },
  { name: '已处理' },
  { name: '已取消' },
];
const currentTab = ref(0);
const showPicker1 = ref(false);

const columns1 = reactive([
  ['近7天', '近1个月', '近3个月', '近6个月', '近1年'],
]);

// 获取选项卡对应的处理状态
const getTabStatus = (tabIndex: number) => {
  const statusMap = {
    0: -1, // 全部
    1: 0,  // 待处理
    2: 1,  // 已处理
    3: 2   // 已取消
  }
  return statusMap[tabIndex] || -1
}

// 获取状态标签类型
const getStatusTagType = (auditStatus: number) => {
  const typeMap = {
    0: 'info',    // 待指派
    1: 'warning', // 待处理
    2: 'error',   // 驳回
    3: 'info',    // 重新指派
    4: 'success', // 已处理
    5: 'default', // 关闭
    99: 'default' // 取消
  }
  return typeMap[auditStatus] || 'default'
};
// z-paging 组件引用
const paging = ref(null)
// 模态框引用
const checkModalRef = ref(null)
const applyModalRef = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

const handleCheck = (item: any) => {
  // 使用v-model绑定的show属性来控制模态框显示
  showCheckModal.value = true
  // 存储当前编辑的数据
  editingData.value = item
}

const handleApply = (item: any) => {
  // 使用v-model绑定的show属性来控制模态框显示
  showApplyModal.value = true
  // 存储当前编辑的数据
  editingData.value = item
}

// 刷新列表
const handleRefresh = () => {
  paging.value.reload()
}

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

// 处理新增点击事件
const handleAdd = () => {
  showAddModal.value = true
}


// 获取异常泊位列表数据
const queryList = async (pageNo: number, pageSize: number) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize,
    isAuthor: getTabStatus(currentTab.value),
    ...searchParams
  }

  await fetchList(params)
};

const fetchList = async (params: any) => {
  try {
    const result: any = await getErrorBerthList(params)
    const data = result.data
    paging.value.complete(data.records || [])
  } catch (error) {
    paging.value.complete(false)
  }
}


// 搜索按钮点击事件
const handleSearch = () => {
};

// 查看详情
const handleView = (row: any) => {
  // 跳转到详情页逻辑
  console.log('查看详情:', row);
};

// 审核操作
const handleVerify = (row: any) => {
  // 跳转到审核页逻辑
  console.log('审核操作:', row);
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.service-ticket-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  .time-picker {
    width: 400rpx;
    display: flex;
    align-items: center;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }
  }

  &-item {
    display: flex;
    flex: 1;
    justify-content: center;
    align-items: center;
    text-align: center;

    .item-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

/* 列表统计 */
.list-statistics {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.list-statistics .item {
  flex: 1 1 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.list-statistics .label {
  font-size: 14px;
  color: #666;
}

.list-statistics .value {
  font-size: 18px;
  font-weight: bold;
  color: #e9710f;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>